var isEventSelectable = false;
var isHolidaySelectable = false;
var isAttendanceSelectable = true;
var isPendingAttendanceSelectable = true;
var isSubAssesmentSelectable = true;
var isShowToolTip = true;
var isDailyLogSelectable = true;
// To Controller tooltip show

var displayEvents = true;
var displayHoliday = true;
var displayAttendance = true;
var displayPendingAttendance = true;
var displaySubAssesment = true;
var displayDailyLog = true;
var displayNonWorkingDays = true;

var HolidayEvents = new Array();
var schoolEvents = new Array();
var sectionEventDays = new Array();
var pendingAttendanceDays = new Array();
var attendanceDays = new Array();
var subAssesmentDays = new Array();
var dailyLogDays = new Array();
var workingDays = new Array();
var exceptionDays = new Array();

/**  Required for Attendance Details */
var date_sectionId = "";
var date_classId = "";
var dateDetailsUrl;

/**  Required for Holidays and Events Details */
var date_aypId = ""

var weekday = new Array(7);
weekday[0] = "Sun";
weekday[1] = "Mon";
weekday[2] = "Tue";
weekday[3] = "Wed";
weekday[4] = "Thu";
weekday[5] = "Fri";
weekday[6] = "Sat";

var numberStrings = new Array(5);
numberStrings[0] = "first";
numberStrings[1] = "second";
numberStrings[2] = "third";
numberStrings[3] = "fourth";
numberStrings[4] = "fifth";

/**
 * Will Fetch List of School Holidays and School Events
 *
 * Required to Set aypId
 */
function updateHolidaysAndSchoolEvents() {
	console.log("------> fetching holidays and school events", date_aypId);

	jQuery.ajax({
		data : {
			aypId : date_aypId
		},
		url : dateDetailsUrl + "getAcademicEventHoliDays",
		type : "post",
		success : function(result) {
			console.log("holidays result", result);
			HolidayEvents = new Array();
			schoolEvents = new Array();
			sectionEventDays = new Array();

			for (var i = 0; i < result.length; i++) {

				var obj = result[i];
				obj.day = convertDateFormat(obj.day)
				if (result[i].eventType == 0) {
					HolidayEvents.push(obj);
				} else if (result[i].eventType == 1) {
					schoolEvents.push(obj);
				} else if (result[i].eventType == 2) {
					sectionEventDays.push(obj);
				} else if (result[i].eventType == 4) {

					subAssesmentDays.push(obj);
				}

				//HolidaysAndSchoolEventDays.push(convertDateFormat(result[i].day));
			}
			//	common_fetchAttendanceDates()
			console.log("HolidaysAndSchoolEventDays:", HolidayEvents.length, schoolEvents.length, sectionEventDays.length);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error");

		}
	});

}

/**
 * Will Fetch Attendance Dates for Particular Class And Section
 *
 * Will Fetch Sub Section Events as well
 *
 */
function updateAttendanceDates(classId, sectionId, callBackFunction) {
	console.log("fetching attendance pending dates", classId, sectionId);

	/*if (classId == "" || classId == undefined || sectionId == "" || sectionId == undefined) {
	 alert("Plese Set ClassId and sectionId before fetching Attendance");
	 return;
	 } else {*/
	date_sectionId = sectionId;
	date_classId = classId;
	//}

	jQuery.ajax({
		data : {
			classId : date_classId,
			sectionId : date_sectionId

		},
		url : dateDetailsUrl + "getAttendanceSecEventDays",
		type : "post",
		success : function(result) {
			console.log("attendance result", result);
			sectionEventDays = new Array();
			attendanceDays = new Array();

			for (var i = 0; i < result.length; i++) {

				var obj = result[i];
				obj.day = convertDateFormat(obj.day)

				if (result[i].eventType == 2) {
					sectionEventDays.push(obj);
				} else if (result[i].eventType == 3) {
					attendanceDays.push(obj);
				} else if (result[i].eventType == 5) {
					dailyLogDays.push(obj)
				}
			}
			if (callBackFunction) {
				callBackFunction();
			}
			console.log("sectionEventDays:", sectionEventDays);
			console.log("attendanceDays:", attendanceDays);
			console.log("dailyLogDays:", dailyLogDays);

			if (displayNonWorkingDays) {
				fetchNonWorkingDays();
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error");

		}
	});

}

/**
 * Will Fetch Working and Non Working days(Sunday to Saturday) details with Exceptions
 *
 */
function fetchNonWorkingDays() {
	console.log("loading schedules");
	jQuery.ajax({
		data : {
			classId : date_classId
		},
		url : dateDetailsUrl + "getScheduleDetailsByClass",
		type : "post",
		success : function(result) {
			console.log("fetchNonWorkingDays result", result);
			workingDays = new Array();
			exceptionDays = new Array();
			var jsonData = jQuery.parseJSON(result.toString())
			console.log("json data:", jsonData);
			console.log("Length:", jsonData[0].daysOfWeek.length);
			for (var i = 0; i < jsonData.length; i++) {
				for (var j = 0; j < jsonData[i].daysOfWeek.length; j++) {
					workingDays.push(jsonData[i].daysOfWeek[j].day);
				}

				for (var k = 0; k < jsonData[i].weekExceptions.length; k++) {
					exceptionDays.push(jsonData[i].weekExceptions[k]);
				}
			}

			/*var obj = {
			 "first" : false,
			 "day" : "Wed",
			 "every" : true,
			 "second" : false,
			 "third" : false,
			 "fourth" : false,
			 "fifth" : false
			 }

			 exceptionDays.push(obj);*/
			console.log("workingDays:", workingDays);
			console.log("exceptionDays:", exceptionDays);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error");

		}
	});
}

function updateAllDates() {
	console.log("Updating Dates");
	updateHolidaysAndSchoolEvents();
	if (displayAttendance) {
		updateAttendanceDates();
	}

}

/**
 * Will Highlight dates in Date Control based on Configurations set
 *
 */

function highlightDays(date) {
	console.log("------------>highlightDays");
	//console.log(date);
	var rtnVal = true;
	var rtnClass;
	var rtnToolTip;

	if (displayNonWorkingDays) {
		if (workingDays.indexOf(weekday[date.getDay()]) == -1) {
			return [false];
		}

		for (var i = 0; i < exceptionDays.length; i++) {

			if (exceptionDays[i].day == weekday[date.getDay()]) {
				console.log("day:", exceptionDays[i].day);
				var currentDate = date.getDate();
				if (currentDate % 7 == 0) {
					var weekIndex = numberStrings[Math.floor(currentDate / 7) - 1];
				} else {
					var weekIndex = numberStrings[Math.floor(currentDate / 7)];
				}
				if (exceptionDays[i][weekIndex] == true || exceptionDays[i]['every'] == true) {
					return [false];
				}
			}
		}
	}

	if (displayHoliday) {
		for (var i = 0; i < HolidayEvents.length; i++) {
			if (convertDateToString(date) == HolidayEvents[i].day) {
				rtnVal = isHolidaySelectable;
				rtnClass = "ayp_holiday";
				rtnToolTip = "Holiday: " + HolidayEvents[i].title;
				if (isShowToolTip) {
					return [rtnVal, rtnClass, rtnToolTip];
				} else {
					return [rtnVal, rtnClass];
				}
			}
		}
	}

	if (displayEvents) {
		for (var i = 0; i < schoolEvents.length; i++) {
			if (convertDateToString(date) == schoolEvents[i].day) {
				rtnVal = isEventSelectable;
				rtnClass = "ayp_event";
				rtnToolTip = "Event: " + schoolEvents[i].title;
				if (isShowToolTip) {
					return [rtnVal, rtnClass, rtnToolTip];
				} else {
					return [rtnVal, rtnClass];
				}
			}
		}
	}

	if (displayEvents) {
		for (var i = 0; i < sectionEventDays.length; i++) {
			if (convertDateToString(date) == sectionEventDays[i].day) {
				rtnVal = isEventSelectable;
				rtnClass = "ayp_event";
				rtnToolTip = "Event: " + sectionEventDays[i].title;
				if (isShowToolTip) {
					return [rtnVal, rtnClass, rtnToolTip];
				} else {
					return [rtnVal, rtnClass];
				}
			}
		}
	}

	if (displaySubAssesment) {
		for (var i = 0; i < subAssesmentDays.length; i++) {
			if (convertDateToString(date) == subAssesmentDays[i].day) {
				//console.log("Submative:", subAssesmentDays);
				rtnVal = isSubAssesmentSelectable;
				rtnClass = "ayp_assesment";
				rtnToolTip = "Assesment: Summative Exams";
				if (isShowToolTip) {
					return [rtnVal, rtnClass, rtnToolTip];
				} else {
					return [rtnVal, rtnClass];
				}
			}
		}
	}

	if (displayAttendance) {
		if (date > new Date())// For Upcoming days handling
		{
			return [true, rtnClass];
		}

		for (var i = 0; i < attendanceDays.length; i++) {
			if (convertDateToString(date) == attendanceDays[i].day) {
				rtnVal = isAttendanceSelectable;
				rtnClass = "";
				rtnToolTip = "Attendance: Completed";
				return [rtnVal, rtnClass, rtnToolTip];
			}
		}
	}

	if (displayDailyLog) {

		if (date > new Date())// For Upcoming days handling
		{
			return [true, rtnClass];
		}

		var hasFound = false;
		for (var i = 0; i < dailyLogDays.length; i++) {
			if (convertDateToString(date) == dailyLogDays[i].day) {
				hasFound = true;
			}
		}

		if (!hasFound) {
			rtnVal = isDailyLogSelectable;
			rtnClass = "dailylog_pending";
			rtnToolTip = "Daily Log: Pending";
			return [rtnVal, rtnClass, rtnToolTip];
		}

	}

	if ((date < new Date()) && displayPendingAttendance) {
		rtnVal = isPendingAttendanceSelectable;
		rtnClass = "attendance_pending"
		rtnToolTip = "Attendance: Pending"
	}

	if (isShowToolTip) {
		return [rtnVal, rtnClass, rtnToolTip];
	} else {
		return [rtnVal, rtnClass];
	}

}

/**
 * Will converts date from YYYY-MM-DD to DD/MM/YYYY format
 */
function convertDateFormat(val) {
	var dayArr = val.split("-");

	return ('0' + dayArr[2]).slice(-2) + '/' + ('0' + dayArr[1]).slice(-2) + '/' + dayArr[0];
	//return dayArr[2] + '/' + dayArr[1] + '/' + dayArr[0];
}

/**
 * Will Converts Date to String based on Type
 *
 */
function convertDateToString(val, type) {

	type = type == undefined ? "/" : type;

	//	console.log("convertDateToString:", ('0' + val.getDate()).slice(-2) + '/' + ('0' + (val.getMonth() + 1)).slice(-2) + '/' + val.getFullYear())
	if (type == "-") {
		return val.getFullYear() + '-' + ('0' + (val.getMonth() + 1)).slice(-2) + '-' + ('0' + val.getDate()).slice(-2);
	} else if (type == "/") {
		return ('0' + val.getDate()).slice(-2) + '/' + ('0' + (val.getMonth() + 1)).slice(-2) + '/' + val.getFullYear();
	}
}

jQuery(function() {
	console.log("date controller", date_classId, date_sectionId, displayAttendance, date_aypId);
	date_aypId = jQuery('#aypId').val();

	if (!dateDetailsUrl) {
		if (jQuery('#baseUrl').val()) {
			dateDetailsUrl = jQuery('#dateDetailsUrl').val().replace("DUMMY", "");
		};
	}
	console.log("date control url:",dateDetailsUrl);
	if (date_aypId) {
		updateHolidaysAndSchoolEvents();
	}
	//if (date_sectionId && date_classId && displayAttendance) {
	updateAttendanceDates();
	//	}

	if (date_classId) {
		fetchNonWorkingDays();
	}

})

